package com.windrift.springhibernate.controller;

import com.windrift.springhibernate.model.Income;
import com.windrift.springhibernate.model.IncomeType;
import com.windrift.springhibernate.service.IncomeService;
import com.windrift.springhibernate.service.IncomeTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author xuweigui
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping(value = "/income")
public class IncomeController {
    @Autowired
    private IncomeService incomeService;
    @Autowired
    private IncomeTypeService incomeTypeService;

    @RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void delete(@PathVariable("id") Integer id) {
        incomeService.remove(id);
    }


    @RequestMapping()
    public String execute(Model model) {
        List<Income> incomes = incomeService.findAll();
        model.addAttribute("incomes", incomes);

        List<IncomeType> incomeTypes = incomeTypeService.findAll();
        StringBuilder sb = new StringBuilder();
        sb.append("incomeTypes:[");
        for (IncomeType incomeType : incomeTypes) {
            sb.append(incomeType.toJSON()).append(",");
        }
        sb.append("]");

        return "accounting/IncomeList";
    }

    @RequestMapping("/add")
    @ResponseBody
    public void add(@RequestParam("assetTypeId") Integer assetTypeId,
                    @RequestParam("incomeTypeId") Integer incomeTypeId,
                    @RequestParam("incomeDate") Date incomeDate,
                    @RequestParam("amount") Double amount,
                    @RequestParam("comment") String comment) {
        Income income = new Income();
        income.setAssetTypeId(assetTypeId);
        income.setIncomeTypeId(incomeTypeId);
        income.setIncomeDate(incomeDate);
        income.setAmount(amount);
        income.setComment(comment);
        incomeService.add(income);
    }

     public void setIncomeTypeService(IncomeTypeService incomeTypeService) {
        this.incomeTypeService = incomeTypeService;
    }


    public void setIncomeService(IncomeService incomeService) {
        this.incomeService = incomeService;
    }


}
